<template>
  <div class="mainImage">
     <!-- 主图上传组件 -->
     <h3>主图</h3>
     <el-upload ref="uploadRef" class="upload-demo" :action="data.postUrl"  :on-preview="handlePreview"
            :on-remove="handleRemove" :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed" list-type="picture-card"
            :on-success="mainImageUploadSuccess" :auto-upload="false">
            <template #trigger>
              <el-icon><Plus /></el-icon>
            </template>
          </el-upload>
  </div>
          <div class="subImages">
            <!-- 副图上传组件 -->
            <h3>副图</h3>
            <el-upload ref="subImagesRef" class="upload-demo" :action="data.postUrl" multiple :on-preview="handlePreview"
              :on-remove="handleRemove" :before-remove="beforeRemove" :limit="4" :on-exceed="handleExceed" list-type="picture"  :on-success="subImagesUploadSuccess"
              :auto-upload="false">
              <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
            </el-upload>
            <el-button type="primary" @click="uploadImages">上传所有图片</el-button>
          </div>
</template>

<script setup>
import { ref, reactive, onMounted,watch } from "vue";
import { Plus } from '@element-plus/icons-vue';


const mainImage = ref(null);
const subImages = ref([]);


const data = reactive({
  fileName: "file",//用于指定上传文件的字段名，也就是在后端接收上传文件时需要使用的字段名。在前端发送上传请求时，请求头中会包含该字段名和对应的文件数据，后端就可以通过这个字段名获取到上传的文件数据
  postUrl: ""
})

const uploadRef = ref(null)
const subImagesRef =ref(null)


const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 4, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  )
}

// 文件上传前的钩子函数
const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfert of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

//上传文件成功
const mainImageUploadSuccess = (response, file, fileList) => {
  mainImage.value = response.data
};
const subImagesUploadSuccess = (response, file, fileList) => {
  subImages.value.push(response.data)
};

// 定义emit，用于传递图片到父组件
const emit = defineEmits(["mainImage", "subImages"]);

watch(mainImage, (newValue) => {
  emit("mainImage", newValue);
});
watch(subImages, (newValue) => {
  emit("subImages", newValue);
},{
  deep:true
});

onMounted(async () => {
  data.postUrl = "/api/uploadFile";

});

const uploadImages = () => {
    uploadRef.value.submit();
  subImagesRef.value.submit();
}

</script>